package com.leimo.web_socket2.handler;

import com.leimo.common.Constant;
import com.leimo.dto.ChatInfoDto;
import com.leimo.service.CustomerServiceService;
import com.leimo.service.TouristService;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

import lombok.extern.slf4j.Slf4j;

/**
 * 自定义处理器
 *
 * @author 段誉
 * @create 2019-02-26 14:42
 */
@Component
@Slf4j
public class MyWebSocketHandler extends TextWebSocketHandler {
  private Map<String, WebSocketSession> sessions;
  /**
   * 当前在线人数
   */
  public static int onlineCount = 0;

  /**
   * 客服sessionId
   */
  public static final String CUSTOMER_SERVICE_SESSION_ID = "0";

  @Autowired
  private TouristService touristService;

  @Autowired
  private CustomerServiceService customerServiceService;

  public MyWebSocketHandler() {
    this.sessions = new ConcurrentHashMap<>();
  }

  /**
   * 收到消息
   * @param session
   * @param message
   * @throws Exception
   */
  @Override
  protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    //判断连接是否打开，已关闭则不执行操作
    if (!session.isOpen()) {
      return;
    }

    //解析消息内容
    JSONObject jsonObject = JSONObject.fromObject(message.getPayload());
    //接收方sessionId
    String to = jsonObject.getString("to");

    //消息内容
    String content = jsonObject.getString("content");

    //发送方sessionId
    String from = jsonObject.getString("from");

    //获取发送方信息
    ChatInfoDto info;
    //判断是给客服发消息
    if (to.equals(CUSTOMER_SERVICE_SESSION_ID)) {
//      info = touristService.getInfo();
      jsonObject.put("id", "1");
    } else {
      //不是给客服发消息
//      info = customerServiceService.getInfo();
      jsonObject.put("id", "2");
    }
    log.info("发送方:[{}]-----接收方:[{}]-----消息内容:[{}]", from, to, content);

    jsonObject.remove("to");
    jsonObject.remove("from");
    jsonObject.put("fromid", from);
    jsonObject.put("type", "friend");
    //接收方session信息
    WebSocketSession sessionTo = sessions.get(to);
    if (sessionTo != null) {
      //发送消息
      sessionTo.sendMessage(new TextMessage(jsonObject.toString()));
    }

  }


  /**
   * 在WebSocket连接成功后调用
   * @param session
   * @throws Exception
   */
  @Override
  public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    Object sessionIdObj = session.getAttributes().get(Constant.WEB_SOCKET_SESSION_ID);
    //如果sessionid为空则不执行
    if (Objects.isNull(sessionIdObj)) {
      return;
    }
    String sessionId = String.valueOf(sessionIdObj);
    //保存建立连接的session
    this.sessions.put(sessionId, session);
    try {
      //非客服不读取离线客服消息
      if (!sessionId.equals(CUSTOMER_SERVICE_SESSION_ID)) {
        return;
      }

      //读取客服的离线消息，进行接收
      WebSocketSession webSocketSession = sessions.get(sessionId);
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("content", "还没离线消息");
      jsonObject.put("username", "只是学习学习");
      jsonObject.put("avatar", "http://pic.mjsuo.com/meijiaosuo/common/20180524091126868_338977.png");
      jsonObject.put("fromid", 3);
      jsonObject.put("type", "friend");
      jsonObject.put("id", "6");
      webSocketSession.sendMessage(new TextMessage(jsonObject.toString()));
    } catch (IOException e) {
      log.error("消息发送失败,IO异常:{}", e.getMessage());
    } catch (Exception e) {
      log.error(e.getMessage());
    }

  }

  /**
   * WebSocket连接关闭
   * @param session
   * @param status
   * @throws Exception
   */
  @Override
  public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
    Object sessionIdObj = session.getAttributes().get(Constant.WEB_SOCKET_SESSION_ID);
    //sessionid为空则不删除
    if (Objects.isNull(sessionIdObj)) {
      return;
    }
    sessions.remove(String.valueOf(sessionIdObj));
  }

  /**
   * 获取当前在线人数
   */
  public static synchronized int getOnlineCount() {
    return onlineCount;
  }

  /**
   * 当前在线人数加1
   */
  public static synchronized void addOnlineCount() {
    MyWebSocketHandler.onlineCount++;
  }

  /**
   * 在线人数减1
   */
  public static synchronized void subOnileCount() {
    MyWebSocketHandler.onlineCount--;
  }
}
